﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace Kaesoft.Hospedaje.Common
{
    public class RelayCommand : ICommand
    {
        #region Campos Privados
        readonly Action<object> _execute;
        Func<object, bool> _canExecute;
        bool _canExecuteCache;
        #endregion

        #region Eventos
        public event EventHandler CanExecuteChanged;
        #endregion

        #region Constructor
        /// <summary>
        /// Crea una instancia de la clase RelayCommand
        /// </summary>
        /// <param name="execute">Accion a ser ejecutada</param>
        public RelayCommand(Action<object> execute) : this(execute, null)
        {

        }

        /// <summary>
        /// Crea un nuevo comando
        /// </summary>
        /// <param name="execute">Funcion a ejecutar</param>
        /// <param name="canExecute">Variable que permite la ejecucion</param>
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }
        #endregion

        #region Metodos Publicos
        /// <summary>
        /// Verifica si el comando puede ser ejecutado
        /// </summary>
        /// <param name="parameter">Parametro de ejecucion</param>
        /// <returns>True o False</returns>
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            bool temp = _canExecute == null ? true : _canExecute(parameter);
            if (_canExecuteCache != temp)
            {
                _canExecuteCache = temp;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, new EventArgs());
                }
            }

            return _canExecuteCache;
        }

        /// <summary>
        /// Ejecuta el comando
        /// </summary>
        /// <param name="parameter">Parametro de ejecucion</param>
        public void Execute(object parameter)
        {
            _execute(parameter);
        }
        #endregion
    }
}
